﻿using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using ApiCoreProject.Bll.Interface;
using System.Security.Cryptography;
using System.Dynamic;
using ApiCoreProject.Model.Entities;

namespace ApiCoreProject.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthenticationController : ControllerBase
    {
        private readonly IConfiguration configuration;
        private readonly IUsersServe usersServe;

        public AuthenticationController(IConfiguration configuration, IUsersServe usersServe)
        {
            this.configuration = configuration;
            this.usersServe = usersServe;
        }


        [HttpPost]
        [Route("/Login")]
        public dynamic Login([FromBody] User u)
        {
            dynamic d = new ExpandoObject();
            

            if (string.IsNullOrWhiteSpace(u.LoginName) || string.IsNullOrWhiteSpace(u.LoginPwd))
            {
                d.code = -1;
                d.msg = "账户和密码不能为空！";
            }
            else
            {
                MD5 md5 = MD5.Create();
                string md5pwd = BitConverter.ToString(md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(u.LoginPwd))).Replace("-", null);
                var user = usersServe.Login(u.LoginName, md5pwd);
                if (user != null)
                {
                    if (user.Status)
                    {
                        string role = user.RoleId.ToString();
                        //获取在配置文件中获取Jwt属性设置
                        string key = configuration["JwtSettings:SecurityKey"];
                        string issuer = configuration["JwtSettings:Issuer"];
                        string audience = configuration["JwtSettings:Audience"];
                        string expireminutes = configuration["JwtSettings:ExpireMinutes"];

                        DateTime expires = DateTime.Now.AddMinutes(double.Parse(expireminutes));

                        string token = AuthorizationConn.CreateJwtToken(key, issuer, audience, expires, role);

                        d.code = 1;
                        d.msg = "登录成功！";
                        d.expires = expires;
                        d.token = token;
                        d.user = user;
                    }
                    else {
                        d.code = -3;
                        d.msg = "账户异常或者已被冻结！";
                    }
                    
                }
                else
                {
                    d.code = -2;
                    d.msg = "账户或密码验证失败！";
                }
            }

            return d;

        }
    }
}
